package com.dhj.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dhj.entity.LoginUser;
import com.dhj.entity.User;
import com.dhj.mapper.MenuMapper;
import com.dhj.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author DaHuaJia
 * @Description SpringSecurity的UserDetailsService接口实现类，从数据库中获取用户基本信息和权限信息
 * @Date 2022-03-20 12:56:35
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 根据登录时填写的登录名，查询用户的详细信息和权限。
     * 默认情况下，Security是在内存中查询，用户名固定是user，密码则是随机的，打印在日志中。
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);

        // 如果没有查询到用户信息就抛出异常
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在！");
        }

        // 获取权限列表
        List<String> authList = menuMapper.selectPermsByUserId(user.getId());

        // 把数据封装成UserDetails返回
        return new LoginUser(user, authList);
    }

}
